package com.kingyun.gpsinspection.purificationservice.services.som.innerservice.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cqhilink.api.common.utils.date.DateUtil;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.som.*;
import com.kingyun.gpsinspection.purificationservice.facade.model.File;
import com.kingyun.gpsinspection.purificationservice.facade.model.jsm.RedisValue;
import com.kingyun.gpsinspection.purificationservice.facade.model.som.FacadeDataItem;
import com.kingyun.gpsinspection.purificationservice.facade.model.som.FacadeFatherItem;
import com.kingyun.gpsinspection.purificationservice.facade.model.som.FacadeStep;
import com.kingyun.gpsinspection.purificationservice.facade.model.som.FacadeWorkOrder;
import com.kingyun.gpsinspection.purificationservice.facade.service.som.FacadeWorkOrderService;
import com.kingyun.gpsinspection.purificationservice.facade.service.som.SomFileService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by yangcs on 2017/2/20.
 */
public class FacadeWorkOrderServiceImpl implements FacadeWorkOrderService {

    @Autowired
    private FacadeWorkOrderMapper facadeWorkOrderMapper;
    @Autowired
    private FacadeFatherItemMapper facadeFatherItemMapper;
    @Autowired
    private FacadeDataItemMapper facadeDataItemMapper;
    @Autowired
    private FacadeStepMapper facadeStepMapper;
    @Autowired
    private SomFileService fileService;
    @Autowired
    private OrderResultMapper orderResultMapper;


    /**
     * 根据cellId查询表单表单项
     *
     * @param cellId
     * @return
     */
    @Override
    public List<FacadeFatherItem> getItemsByCellId(String cellId, BigDecimal stepVersion) {
        Map map = new HashMap<>();
        map.put("cellId", cellId);
        map.put("stepVersion", stepVersion);
        return facadeFatherItemMapper.getItemsByCellId(map);
    }

    /**
     * 根据cellId查询步骤(包含结果)
     *
     * @param cellId
     * @param stepVersion
     * @param cellResultId
     * @return
     */
    @Override
    public List<FacadeStep> getStepsByCellId(String cellId, BigDecimal stepVersion, String cellResultId) {
        Map map = new HashMap<>();
        map.put("cellId", cellId);
        map.put("version", stepVersion);
        map.put("cellResultId", cellResultId);
        return facadeStepMapper.getStepsByCellId(map);
    }

    /**
     * 巡回检查时自定义步骤
     *
     * @param workOrderId
     * @param cellResultId
     * @return
     */
    public List<FacadeStep> getStepNoCellId(String workOrderId, String cellResultId) {
        Map map = new HashMap<>();
        map.put("workOrderId", workOrderId);
        map.put("cellResultId", cellResultId);
        return facadeStepMapper.getStepNoCellId(map);
    }

    /**
     * 巡回检查时自定义步骤第二版本 未完成
     *
     * @param workOrderId
     * @return
     */
    public List<FacadeStep> getStepNoCellIdByCategory(String workOrderId) {
        Map map = new HashMap<>();
        map.put("workOrderId", workOrderId);
        return facadeStepMapper.getStepNoCellIdByCategory(map);
    }

    /**
     * 巡回检查时自定义步骤第二版本 已完成
     *
     * @param workOrderId
     * @param cellResultId
     * @return
     */
    public List<FacadeStep> getStepNoCellIdByCategory(String workOrderId, String cellResultId) {
        Map map = new HashMap<>();
        map.put("workOrderId", workOrderId);
        map.put("cellResultId", cellResultId);
        return facadeStepMapper.getStepNoCellIdByCategory2(map);
    }

    /**
     * 根据表单项Id查询数据项
     *
     * @param fatherId
     * @param cellResuleId
     * @return
     */
    @Override
    public List<FacadeDataItem> getDataItemsByFatherId(String fatherId, String cellResuleId) {
        Map map = new HashMap<>();
        map.put("fatherId", fatherId);
        map.put("cellResuleId", cellResuleId);
        return facadeDataItemMapper.getDataItemsByFatherId(map);
    }

    /**
     * 根据步骤Id查询数据项
     *
     * @param stepId
     * @param stepResultId
     * @return
     */
    @Override
    public List<FacadeDataItem> getDataItemsByStepId(String stepId, String stepResultId) {
        Map map = new HashMap<>();
        map.put("stepId", stepId);
        map.put("stepResultId", stepResultId);
        return facadeDataItemMapper.getDataItemsByStepId(map);
    }

    /**
     * 同步工单
     *
     * @param userId     用户id
     * @param updateTime 更新时间戳
     * @param status     0全部，1今日，2遗留
     * @return
     */
    @Override
    public List<FacadeWorkOrder> getOrders(String userId, long updateTime, int status) {
        Map map = new HashMap<>();
        map.put("modifyTime", DateUtil.DateToString(new Date(updateTime), "yyyy-MM-dd HH:mm:ss"));
        map.put("userId", userId);
        map.put("status", status);
        List<FacadeWorkOrder> orders = facadeWorkOrderMapper.getOrders(map);
        List<FacadeWorkOrder> newOrders = new ArrayList<>();
        if (orders != null && orders.size() > 0) {
            for (FacadeWorkOrder order : orders) {
                newOrders.add(createWorkOrder(order));
            }
        }
        return newOrders;
    }

    /**
     * 获取工单台帐
     *
     * @param userId
     * @param limit
     * @param offset
     * @return
     */
    @Override
    public JSONObject getWeekAndMouth(String userId, Integer limit, Integer offset) {
        Map map = new HashMap<>();
        JSONObject jsonObject = new JSONObject();
        map.put("userId", userId);
        map.put("limit", limit);
        map.put("offset", offset);
        jsonObject.put("total", facadeWorkOrderMapper.getWeekAndMouthCount(map));
        jsonObject.put("rows", JSON.toJSON(facadeWorkOrderMapper.getWeekAndMouth(map)));
        return jsonObject;
    }

    /**
     * 获取待办工单数量
     *
     * @param userId
     * @param updateTime
     * @return
     */
    @Override
    public int getDeal(String userId, long updateTime) {
        Map map = new HashMap<>();
        map.put("modifyTime", DateUtil.DateToString(new Date(updateTime), "yyyy-MM-dd HH:mm:ss"));
        map.put("userId", userId);
        map.put("status", 0);
        List<FacadeWorkOrder> orders = facadeWorkOrderMapper.getOrders(map);
        if (orders != null && orders.size() > 0) {
            return orders.size();
        } else {
            return 0;
        }
    }

    /**
     * 查询工单信息
     *
     * @param workOrderId
     * @return
     */
    @Override
    public FacadeWorkOrder getOrderById(String workOrderId) {
        return createWorkOrder(facadeWorkOrderMapper.getOrderById(workOrderId));
    }

    /**
     * 构造工单信息
     *
     * @param order
     * @return
     */
    @Override
    public FacadeWorkOrder createWorkOrder(FacadeWorkOrder order) {
        // 获取操作单元表单项
        List<FacadeFatherItem> ffi = getItemsByCellId(order.getCellId(), order.getStepVersion());
        List<FacadeFatherItem> newFfi = new ArrayList<>();
        if (ffi != null && ffi.size() > 0) {
            for (FacadeFatherItem item : ffi) {
                // 获取表单项对应的数据项信息
                item.setDataItems(getDataItemsByFatherId(item.getFatherItemId(), order.getCellResultId()));
                newFfi.add(item);
            }
            // 工单赋值操作单元表单
            order.setItems(newFfi);
        }
        // 操作单元数据集 // TODO: 2017/3/27
        order.setDatas(null);
        // 获取操作单元步骤信息
        List<FacadeStep> fc;
        if (StringUtils.isNotBlank(order.getCellId())) {
            fc = getStepsByCellId(order.getCellId(), order.getStepVersion(), order.getCellResultId());
        } else {
            // 自定义巡检 2个版本
            int category = facadeWorkOrderMapper.getCategoryById(order.getWorkOrderId());
            // 为0表示是第一版本，保存工单对应的stepId
            if (category == 0) {
                fc = getStepNoCellId(order.getWorkOrderId(), order.getCellResultId());
            } else {
                // 不为0表示为第二版本，保存工单对应标准的id和大类
                if (StringUtils.isBlank(order.getCellResultId())) {
                    // 工单未完成
                    fc = getStepNoCellIdByCategory(order.getWorkOrderId());
                } else {
                    // 工单已经完成
                    fc = getStepNoCellIdByCategory(order.getWorkOrderId(), order.getCellResultId());
                }
            }
        }
        List<FacadeStep> newFc = new ArrayList<>();
        if (fc != null && fc.size() > 0) {
            for (FacadeStep step : fc) {
                // 步骤对应的数据项信息
                step.setDataItems(getDataItemsByStepId(step.getStepId(), step.getStepResultId()));
                // 步骤对应的图片信息
                step.setStepFiles(fileService.findByBusiness(step.getStepId()));
                // 完成步骤上传的图片
                step.setImgs(fileService.findByBusiness(step.getStepResultId(), File.IMG_TYPE));
                // 完成步骤上传的视频
                step.setMp4s(fileService.findByBusiness(step.getStepResultId(), File.MP4_TYPE));
                newFc.add(step);
            }
            // 工单赋值步骤
            order.setSteps(newFc);
        }
        return order;
    }

    /**
     * 获取工单
     *
     * @param workOrderId
     * @return
     */
    @Override
    public FacadeWorkOrder getOrder(String workOrderId) {
        FacadeWorkOrder workOrder = facadeWorkOrderMapper.getOrderById(workOrderId);
        // 当工单已完成时，查询工单的执行步骤，表单数据项，语音，视频，图片，rfid，工单总耗时，工单最长执行步骤
        String cellResultId = workOrder.getCellResultId();
        if (StringUtils.isNotBlank(cellResultId)) {
            // 工单的执行步骤
            workOrder.setStepNums(orderResultMapper.queryStepNums(cellResultId));
            // 工单表单数据项
            workOrder.setDataItemNums(orderResultMapper.queryDataItemNums(cellResultId));
            // 工单视频
            workOrder.setVideoNums(orderResultMapper.queryVideoNums(cellResultId));
            // 工单图片
            workOrder.setPicNums(orderResultMapper.queryPicNums(cellResultId));
            // rfid
            workOrder.setRfids(orderResultMapper.queryRfids(cellResultId));
            if (workOrder.getFinishType() != 2) {
                // 总耗时
                workOrder.setTotalCost(orderResultMapper.queryTotalCost(cellResultId));
                // 最长步骤
                workOrder.setLonggestStep(orderResultMapper.queryLonggestStep(cellResultId));
            }
        }
        return workOrder;
    }

    /**
     * 首页工单统计
     *
     * @return
     */
    @Override
    public JSONArray getOrderCount(RedisValue redisValue) {
        String orgId = redisValue.getEmployeeVo().getOrgId();
        List<HashMap> list = facadeWorkOrderMapper.getOrder(orgId);
        JSONArray array = new JSONArray();
        JSONObject obj;
        if (list != null && list.size() > 0) {
            for (HashMap map : list) {
                obj = new JSONObject();
                obj.put("name", map.get("TASK_TYPE_NAME"));
                obj.put("value", map.get("NUMS"));
                array.add(obj);
            }
        }
        return array;
    }

    /**
     * 未超期未完成的工单总数
     *
     * @param redisValue
     * @return
     */
    @Override
    public int getUnFinishOrder(RedisValue redisValue) {
        String orgId = redisValue.getEmployeeVo().getOrgId();
        return facadeWorkOrderMapper.getUnFinishOrder(orgId);
    }

    /**
     * 获取终止任务关联的工单
     *
     * @param userId
     * @param updateTime
     * @return
     */
    @Override
    public List<String> getInvalid(String userId, long updateTime) {
        Map map = new HashMap<>();
        map.put("modifyTime", DateUtil.DateToString(new Date(updateTime), "yyyy-MM-dd HH:mm:ss"));
        map.put("userId", userId);
        return facadeWorkOrderMapper.getInvalid(map);
    }
}
